package com.draemoncode.weixindb.server;

import com.draemoncode.weixindb.constant.CharConstant;
import com.draemoncode.weixindb.constant.ShowMessageConstant;
import com.draemoncode.weixindb.constant.UIMessageTypeConstant;
import com.draemoncode.weixindb.util.JvmUtil;
import com.draemoncode.weixindb.websocket.UIMessage;
import com.draemoncode.weixindb.websocket.UISession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@ChannelHandler.Sharable
@Component
@Slf4j
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {

    @Autowired
    private EventCallClient eventCallClient;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        CSession.setChannelHandlerContext(ctx);
        log.info("机器人客户端连接: " + ctx.toString());
        UIMessage uiMessage = new UIMessage();
        uiMessage.setType(UIMessageTypeConstant.SHOW);
        uiMessage.getMsg().put(ShowMessageConstant.RESPONSE_SHOW_CONTENT, "机器人已连接");
        UISession.send(uiMessage);
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        log.info("收到机器人客户端消息: " + request);
        EventValue eventValue = new EventValue();
        eventValue.setEvent(request);
        eventCallClient.event(eventValue);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.info("机器人客户端异常: " + JvmUtil.printHTMLStackTrace(cause, CharConstant.HTML_NEW_LINE_CHAR));
    }
}
